package main

import (
	//"fmt"
	"net"
	"net/http"
	"log"
	"encoding/json"
	"os"
)


func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	//w.WriteString("ok")
    //w.Header().Set("Name", "m")
	log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
	log.Println(r.Header)
}
	
//遍历client  request header
func json_rsp(w http.ResponseWriter, r *http.Request) {
	h := r.Header
	json_head, err := json.Marshal(h)

	if err == nil {
		w.Header().Set("rep",string(json_head))
	}
	log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate )
	log.Println(json_head )
    log.Println(os.Getenv("VERSION") )
	log.Println(GetRemoteClientIp(r))
}

// GetRemoteClientIp 获取远程客户端IP
func GetRemoteClientIp(r *http.Request) string {
	remoteIp := r.RemoteAddr

	if ip := r.Header.Get("X-Real-IP"); ip != "" {
		remoteIp = ip
	} else if ip = r.Header.Get("X-Forwarded-For"); ip != "" {
		remoteIp = ip
	} else {
		remoteIp, _, _ = net.SplitHostPort(remoteIp)
	}

	//本地ip
	if remoteIp == "::1" {
		remoteIp = "127.0.0.1"
	}

	return remoteIp
}

func main()	{
	server := http.Server{
        Addr: "0.0.0.0:8080",
    }
    http.HandleFunc("/json_rsp", json_rsp)
	http.HandleFunc("/healthz", healthz)
    server.ListenAndServe()
}